<template>
  <div class="forgot-password-page">
    <Header />

    <!-- 忘记密码内容区域 -->
    <div class="forgot-password-content">
      <div class="container">
        <div class="forgot-password-wrapper">
          <!-- 左侧品牌信息 -->
          <div class="brand-section">
            <div class="brand-content">
              <img src="@/assets/logo-full.png" alt="六堡茶" class="brand-logo" />
              <h2 class="brand-title">找回密码</h2>
              <p class="brand-desc">请按照以下步骤重置您的密码</p>
              <div class="steps-indicator">
                <div class="step" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
                  <div class="step-number">1</div>
                  <span class="step-text">验证手机</span>
                </div>
                <div class="step" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
                  <div class="step-number">2</div>
                  <span class="step-text">验证身份</span>
                </div>
                <div class="step" :class="{ active: currentStep >= 3, completed: currentStep > 3 }">
                  <div class="step-number">3</div>
                  <span class="step-text">重置密码</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧表单区域 -->
          <div class="form-section">
            <div class="form-container">
              <!-- 步骤1：输入手机号 -->
              <div v-if="currentStep === 1" class="step-content">
                <div class="form-header">
                  <h3 class="form-title">验证手机号</h3>
                  <p class="form-subtitle">请输入您注册时使用的手机号</p>
                </div>

                <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneRules" class="forgot-form">
                  <el-form-item prop="phone">
                    <el-input v-model="phoneForm.phone" placeholder="请输入手机号" size="large" prefix-icon="Phone" clearable />
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" size="large" class="submit-btn" :loading="loading" @click="handlePhoneSubmit">
                      {{ loading ? '验证中...' : '下一步' }}
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 步骤2：验证码验证 -->
              <div v-if="currentStep === 2" class="step-content">
                <div class="form-header">
                  <h3 class="form-title">验证身份</h3>
                  <p class="form-subtitle">验证码已发送至 {{ maskPhone(phoneForm.phone) }}</p>
                </div>

                <el-form ref="verifyFormRef" :model="verifyForm" :rules="verifyRules" class="forgot-form">
                  <el-form-item prop="verifyCode">
                    <div class="verify-code-wrapper">
                      <el-input
                        v-model="verifyForm.verifyCode"
                        placeholder="请输入6位验证码"
                        size="large"
                        prefix-icon="Message"
                        clearable
                        maxlength="6" />
                      <el-button class="verify-btn" :disabled="countdown > 0" @click="resendCode">
                        {{ countdown > 0 ? `${countdown}s后重发` : '重新发送' }}
                      </el-button>
                    </div>
                  </el-form-item>

                  <el-form-item>
                    <div class="button-group">
                      <el-button size="large" @click="goBack">上一步</el-button>
                      <el-button type="primary" size="large" class="submit-btn" :loading="loading" @click="handleVerifySubmit">
                        {{ loading ? '验证中...' : '下一步' }}
                      </el-button>
                    </div>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 步骤3：重置密码 -->
              <div v-if="currentStep === 3" class="step-content">
                <div class="form-header">
                  <h3 class="form-title">重置密码</h3>
                  <p class="form-subtitle">请设置您的新密码</p>
                </div>

                <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" class="forgot-form">
                  <el-form-item prop="newPassword">
                    <el-input
                      v-model="passwordForm.newPassword"
                      type="password"
                      placeholder="请输入新密码"
                      size="large"
                      prefix-icon="Lock"
                      show-password
                      clearable />
                  </el-form-item>

                  <el-form-item prop="confirmPassword">
                    <el-input
                      v-model="passwordForm.confirmPassword"
                      type="password"
                      placeholder="请确认新密码"
                      size="large"
                      prefix-icon="Lock"
                      show-password
                      clearable />
                  </el-form-item>

                  <el-form-item>
                    <div class="button-group">
                      <el-button size="large" @click="goBack">上一步</el-button>
                      <el-button type="primary" size="large" class="submit-btn" :loading="loading" @click="handlePasswordSubmit">
                        {{ loading ? '重置中...' : '完成重置' }}
                      </el-button>
                    </div>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 步骤4：完成提示 -->
              <div v-if="currentStep === 4" class="step-content success-content">
                <div class="success-icon">✓</div>
                <h3 class="success-title">密码重置成功！</h3>
                <p class="success-desc">您的密码已成功重置，请使用新密码登录</p>
                <el-button type="primary" size="large" class="submit-btn" @click="goToLogin"> 立即登录 </el-button>
              </div>

              <!-- 返回登录链接 -->
              <div v-if="currentStep < 4" class="form-footer">
                <span class="back-text">想起密码了？</span>
                <router-link to="/login" class="back-link">返回登录</router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import apiUser from '@/api/modules/user'

  const router = useRouter()
  const phoneFormRef = ref()
  const verifyFormRef = ref()
  const passwordFormRef = ref()
  const loading = ref(false)
  const countdown = ref(0)
  const currentStep = ref(1)

  // 表单数据
  const phoneForm = reactive({
    phone: '',
  })

  const verifyForm = reactive({
    verifyCode: '',
  })

  const passwordForm = reactive({
    newPassword: '',
    confirmPassword: '',
  })

  // 自定义验证函数
  const validatePhone = (rule, value, callback) => {
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }

  const validateConfirmPassword = (rule, value, callback) => {
    if (value !== passwordForm.newPassword) {
      callback(new Error('两次输入的密码不一致'))
    } else {
      callback()
    }
  }

  // 表单验证规则
  const phoneRules = {
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: validatePhone, trigger: 'blur' },
    ],
  }

  const verifyRules = {
    verifyCode: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { len: 6, message: '验证码为6位数字', trigger: 'blur' },
    ],
  }

  const passwordRules = {
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
      { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字', trigger: 'blur' },
    ],
    confirmPassword: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { validator: validateConfirmPassword, trigger: 'blur' },
    ],
  }

  // 手机号掩码显示
  const maskPhone = (phone) => {
    if (!phone) return ''
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }

  // 处理手机号提交
  const handlePhoneSubmit = async () => {
    if (!phoneFormRef.value) return

    try {
      const valid = await phoneFormRef.value.validate()
      if (!valid) return

      loading.value = true

      apiUser
        .GetResetVerifyCode({
          mobile: phoneForm.phone,
        })
        .then(async (res) => {
          // 发送验证码
          ElMessage.success('验证码已发送到您的手机')

          // 开始倒计时
          startCountdown()

          // 进入下一步
          currentStep.value = 2
        })
    } catch (error) {
      console.error('手机号验证失败:', error)
      ElMessage.error('手机号不存在或验证失败')
    } finally {
      loading.value = false
    }
  }

  // 处理验证码提交
  const handleVerifySubmit = async () => {
    if (!verifyFormRef.value) return

    try {
      const valid = await verifyFormRef.value.validate()
      if (!valid) return

      loading.value = true

      apiUser
        .SubmitVerifyCode({
          mobile: phoneForm.phone,
          captcha: verifyForm.verifyCode,
        })
        .then(async (res) => {
          ElMessage.success('验证码验证成功')

          // 进入下一步
          currentStep.value = 3
        })
        .catch((err) => {})
    } catch (error) {
      console.error('验证码验证失败:', error)
      ElMessage.error('验证码错误或已过期')
    } finally {
      loading.value = false
    }
  }

  // 处理密码重置提交
  const handlePasswordSubmit = async () => {
    if (!passwordFormRef.value) return

    try {
      const valid = await passwordFormRef.value.validate()
      if (!valid) return

      loading.value = true

      apiUser
        .ResetPassword({
          mobile: phoneForm.phone,
          captcha: verifyForm.verifyCode,
          newpassword: passwordForm.newPassword,
        })
        .then(async (res) => {
          ElMessage.success('密码重置成功！')

          // 进入完成步骤
          currentStep.value = 4
        })
        .catch((err) => {})
    } catch (error) {
      console.error('密码重置失败:', error)
      ElMessage.error('密码重置失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }

  // 重新发送验证码
  const resendCode = async () => {
    try {
      apiUser
        .GetVerifyCode({
          mobile: phoneForm.phone,
        })
        .then(async (res) => {
          ElMessage.success('验证码已重新发送')
          startCountdown()
        })
        .catch((err) => {})
    } catch (error) {
      console.error('重新发送验证码失败:', error)
      ElMessage.error('发送失败，请稍后重试')
    }
  }

  // 开始倒计时
  const startCountdown = () => {
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }

  // 返回上一步
  const goBack = () => {
    if (currentStep.value > 1) {
      currentStep.value--
    }
  }

  // 跳转到登录页面
  const goToLogin = () => {
    router.push('/login')
  }
</script>

<style scoped>
  .forgot-password-page {
    min-height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  }

  .forgot-password-content {
    padding: 60px 0;
    min-height: calc(100vh - 200px);
    display: flex;
    align-items: center;
  }

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }

  .forgot-password-wrapper {
    display: flex;
    background: white;
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    min-height: 600px;
  }

  /* 左侧品牌区域 */
  .brand-section {
    flex: 1;
    background: linear-gradient(135deg, #1c705e 0%, #2d8a6e 100%);
    color: white;
    padding: 60px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .brand-content {
    text-align: center;
    max-width: 400px;
  }

  .brand-logo {
    width: 120px;
    height: auto;
    margin-bottom: 30px;
    background: white;
    padding: 15px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .brand-title {
    font-size: 32px;
    font-weight: 600;
    margin-bottom: 16px;
    color: white;
  }

  .brand-desc {
    font-size: 16px;
    opacity: 0.9;
    margin-bottom: 40px;
    line-height: 1.6;
  }

  /* 步骤指示器 */
  .steps-indicator {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .step {
    display: flex;
    align-items: center;
    gap: 12px;
    opacity: 0.5;
    transition: all 0.3s;
  }

  .step.active {
    opacity: 1;
  }

  .step.completed {
    opacity: 0.8;
  }

  .step-number {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-weight: 600;
  }

  .step.active .step-number {
    background: white;
    color: #1c705e;
  }

  .step.completed .step-number {
    background: #4ade80;
    color: white;
  }

  .step-text {
    font-size: 14px;
    font-weight: 500;
  }

  /* 右侧表单区域 */
  .form-section {
    flex: 1;
    padding: 60px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .form-container {
    width: 100%;
    max-width: 400px;
  }

  .step-content {
    min-height: 300px;
  }

  .form-header {
    text-align: center;
    margin-bottom: 40px;
  }

  .form-title {
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }

  .form-subtitle {
    color: #666;
    font-size: 14px;
  }

  .forgot-form {
    margin-bottom: 30px;
  }

  .forgot-form .el-form-item {
    margin-bottom: 24px;
  }

  .verify-code-wrapper {
    display: flex;
    gap: 12px;
  }

  .verify-code-wrapper .el-input {
    flex: 1;
  }

  .verify-btn {
    white-space: nowrap;
    min-width: 120px;
  }

  .button-group {
    display: flex;
    gap: 12px;
  }

  .button-group .el-button {
    flex: 1;
    height: 48px;
    font-size: 16px;
  }

  .submit-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 600;
    background: #1c705e;
    border-color: #1c705e;
  }

  /* 在button-group中的submit-btn不使用width: 100% */
  .button-group .submit-btn {
    width: auto;
  }

  .submit-btn:hover {
    background: #2d8a6e;
    border-color: #2d8a6e;
  }

  /* 成功页面 */
  .success-content {
    text-align: center;
    padding: 40px 0;
  }

  .success-icon {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: #4ade80;
    color: white;
    font-size: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 30px;
  }

  .success-title {
    font-size: 24px;
    color: #333;
    margin-bottom: 16px;
  }

  .success-desc {
    color: #666;
    margin-bottom: 40px;
    line-height: 1.6;
  }

  .form-footer {
    text-align: center;
    font-size: 14px;
    color: #666;
  }

  .back-link {
    color: #1c705e;
    text-decoration: none;
    font-weight: 600;
    margin-left: 8px;
  }

  .back-link:hover {
    text-decoration: underline;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .forgot-password-wrapper {
      flex-direction: column;
      margin: 20px;
    }

    .brand-section {
      padding: 40px 20px;
    }

    .form-section {
      padding: 40px 20px;
    }

    .brand-title {
      font-size: 24px;
    }

    .form-title {
      font-size: 24px;
    }

    .steps-indicator {
      flex-direction: row;
      justify-content: center;
      gap: 30px;
    }

    .step {
      flex-direction: column;
      gap: 8px;
    }

    .step-text {
      font-size: 12px;
    }

    .verify-code-wrapper {
      flex-direction: column;
    }

    .verify-btn {
      min-width: auto;
    }

    .button-group {
      flex-direction: column;
    }
  }

  @media (max-width: 480px) {
    .forgot-password-content {
      padding: 20px 0;
    }

    .container {
      padding: 0 10px;
    }

    .brand-section,
    .form-section {
      padding: 30px 15px;
    }
  }
</style>
